package com.study.advice.demo.introduction;

import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.support.DelegatingIntroductionInterceptor;

public class ControllablePerformanceMonitor extends DelegatingIntroductionInterceptor implements Monitorable {
    private static final long serialVersionUID = 4998832881038290826L;
    //保存性能监控功能的开关，通过 ThreadLocal，会让每一个线程都能够单独使用一个状态
    private ThreadLocal<Boolean> monitorStatuses = new ThreadLocal<Boolean>();

    @Override
    public void setActive(boolean active) {
        monitorStatuses.set(active);
    }

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        Object obj = null;
        //开启性能监控
        if (monitorStatuses.get() != null && monitorStatuses.get()) {
            PerformanceMonitor.begin(invocation.getClass().getName() + "." + invocation.getMethod().getName());
            obj = super.invoke(invocation);
            PerformanceMonitor.end();
        } else {
            obj = super.invoke(invocation);
        }
        return obj;
    }
}
